package com.lcz.suanfa.经典算法;

import org.junit.Test;

import java.util.Arrays;

/**
 * <pre>
 * <img width="128" height="110" src="https://tse3-mm.cn.bing.net/th/id/OIP-C.en-w_oH-yn2UsSRfWnOsGAHaGY?w=198&h=180&c=7&r=0&o=5&dpr=1.25&pid=1.7" alt="马刺">
 * 作者:     <a href="https://github.com/liuchuanzheng">刘传政</a>
 * 创建时间:  17:03 2022/2/21 0021
 * QQ:      1052374416
 * 电话:     18501231486
 * 描述:
 * </pre>
 */
public class 查找 {
    @Test
    public void test_二分查找() {
        int[] nums = {0, 20, 30, 40, 50, 60};
        int i = halfSearch(nums, 20);
        System.out.println(i+"");
    }

    //循环实现二分查找算法arr 已排好序的数组x 需要查找的数-1 无法查到数据
    public static int halfSearch(int[] srcArray, int des) {
        //定义初始最小、最大索引
        int low = 0;
        int high = srcArray.length - 1;
        //确保不会出现重复查找，越界
        while (low <= high) {
            //计算出中间索引值
            int middle = (high + low) /2;
            if (des == srcArray[middle]) {
                return middle;
            } else if (des < srcArray[middle]) {
                high = middle - 1;
            } else {
                low = middle + 1;
            }
        }
        //若没有，则返回-1
        return -1;
    }

}
